import axios from 'axios'
import store from '../store'
import {getToken} from './auth'
import {Router, useRouter} from "vue-router";
import Config from "@/config/Config";
// create an axios instance
const service = axios.create({
    baseURL: Config.apiName, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    (config: any) => {
        // do something before request is sent
        const token = getToken()
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token
        }
        store.commit('app/changeLoading', true)
        return config
    },
    (error: any) => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    (response: any) => {
        const status = response.status
        const res = response.data
        const router: Router = useRouter()


        // if the custom code is not 20000, it is judged as an error.
        if (status !== 200) {
            store.commit('app/changeLoading', false)
            return Promise.reject(new Error(res.message || 'Error'))
        }
        if (response.headers.token) {
            // setToken(response.headers.token)
        }

        if (res.code === 401) {
            router.push({path: 'user/login'})
            return
        }
        if (res.code !== 200) {

            store.commit('app/changeLoading', false)
            return Promise.reject(new Error(res.message || 'Error'))
        }
        store.commit('app/changeLoading', false)

        return res
    },
    (error: any) => {
        store.commit('app/changeLoading', false)
        return Promise.reject(error)
    }
)

export default service
